import React from 'react';
import { InputItem, Toast, TextareaItem } from 'antd-mobile';
import { createForm } from 'rc-form';
import Star from '../star';
import './index.less';

function SelfInput(props) {
  const {
    form,
    label,
    isRequired = true,
    unit,
    handleInputChange,
    rule: { len, empty, error, reg },
    field,
    placeholder = '请输入',
    type,
    defaultValue = '',
    rows,
    disabled = false,
  } = props;
  const { getFieldProps, getFieldError } = form;
  const validate = (rule, val, callback) => {
    let value = val.replace(/ /g, '');
    if (value.length >= len) {
      if (typeof reg === 'undefined') {
        handleInputChange && handleInputChange(value, label, field && field);
      } else {
        if (reg.test(value)) {
          handleInputChange && handleInputChange(value, label, field && field);
        } else {
          callback(new Error(error));
        }
      }
    } else if (value.length === 0) {
      callback(new Error(empty));
    } else {
      callback(new Error(error));
    }
  };
  return (
    <div className="selfInput">
      {isRequired ? <Star /> : <div style={{ marginRight: '0.17rem' }}></div>}
      {type !== 'textarea' ? (
        <InputItem
          {...getFieldProps('val', {
            rules: [{ validator: validate }],
            initialValue: defaultValue,
          })}
          error={!!getFieldError('val')}
          onErrorClick={() => {
            Toast.info(getFieldError('val'), 1);
          }}
          type={type}
          clear
          placeholder={placeholder}
          extra={unit && unit}
          disabled={disabled}
        >
          <span>{label}</span>
        </InputItem>
      ) : (
        <TextareaItem
          {...getFieldProps('val', {
            rules: [{ validator: validate }],
          })}
          error={!!getFieldError('val')}
          onErrorClick={() => {
            Toast.info(getFieldError('val'), 1);
          }}
          clear
          placeholder={placeholder}
          rows={parseInt(rows || 3)}
          title={label}
          defaultValue={defaultValue}
          disabled={disabled}
        ></TextareaItem>
      )}
    </div>
  );
}
export default createForm()(SelfInput);
